/**
 * 3D 展示
 * 
 * @author Gill Gong
 */

 import React from "react"
 import { GLView } from "expo-gl"
 import { Asset } from "expo-asset"
 import ExpoTHREE,{ THREE } from "expo-three"
 import * as FileSystem from "expo-file-system"
 import { View, PixelRatio, Alert } from "react-native"
//import console = require("console");

 class J3DView extends React.Component {
  
  static navigationOptions = () => {
    
    return {
      title: '3D View'
    }
  }

  constructor(options) {

    super(options)
  }

  render() {
    let { height } = Jw.getClientWidthAndHeight()
 
    //Indeed, there is a bug in our code but it occurs only when one of the GLView's dimension equals to 0. 
    //Looks like it can be fixed easily in your JS code by setting a height of the GLView to a non-zero value.
    return (
      <View>
        <GLView
        height={ height }
        style={{ height: height }}
        onContextCreate={ (gl) => this.onGlContextCreate(gl) } />
      </View>
    )
  }

  async onGlContextCreate(gl) {
    let { width, height } = Jw.getClientWidthAndHeight()
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(
      75, width/height, 0.1, 1000
    );
    const renderer = new ExpoTHREE.Renderer({ gl });
    renderer.setPixelRatio(PixelRatio.get());
    renderer.setSize(width, height);
    
    let skyFile = Asset.fromModule(require("~/assets/imgs/sky.png"))
    // await skyFile.downloadAsync()
    
    // Alert.alert(
    //   'Info', 
    //   skyFile.localUri,
    //   [{ text: '确认', onPress: ()=>{} }]
    // )

    let textureAssets = await ExpoTHREE.loadAsync(skyFile)
    //let textureAssets = await ExpoTHREE.loadAsync("file:///android_asset/imgs/sky.png")
    
    const geometry = new THREE.SphereBufferGeometry(1, 36, 36);
    const material = new THREE.MeshBasicMaterial({
      map: textureAssets
    });
    const sphere = new THREE.Mesh(geometry, material);    
    sphere.position.x = 0
    sphere.position.y = 2  
    sphere.position.z = 0
    scene.add(sphere);
    scene.add(new THREE.GridHelper(5, 10))
    camera.position.z = 5;
    camera.position.y = 1

    const render = () => {
      requestAnimationFrame(render);
      sphere.rotation.x += 0.01;
      sphere.rotation.y += 0.01;
      renderer.render(scene, camera);
      gl.endFrameEXP();
    };

    render();
  }

  // bundled asset uri's become `asset://...` in production build, but expo-gl
  // cannot handle them, https://github.com/expo/expo/issues/2693
  // this workaround copies them to a known path files so we can use a regular
  // `file://...` uri instead.
  async copyAssetToCacheAsync(assetModule, localFilename) {
    const localUri = `${FileSystem.cacheDirectory}asset_${localFilename}`;
    const fileInfo = await FileSystem.getInfoAsync(localUri, { size: false });

    if (!fileInfo.exists) {
      const asset = Asset.fromModule(assetModule);
      await asset.downloadAsync();
      console.log(`copyAssetToCacheAsync ${asset.localUri} -> ${localUri}`);
      await FileSystem.copyAsync({
        from: asset.localUri,
        to: localUri,
      });
    }

    return localUri;
  }

 }

 export default J3DView
